package com.zhuzi.guicollect.ui;

import com.zhuzi.guicollect.jsl.GetPage;
import com.zhuzi.guicollect.utils.AlertUtils;
import com.zhuzi.guicollect.utils.ThreadPools;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.TextField;
import javafx.stage.DirectoryChooser;
import lombok.extern.slf4j.Slf4j;

import java.io.File;

/**
 * @Author: MI
 * @Date: 2021/10/24/20:46
 * @Description:
 */
@Slf4j
public class CollController {
    @FXML
    public Button dirSelBtn;
    @FXML
    public CheckBox onlyPublishCheck;
    @FXML
    public CheckBox onlyPageCheck;
    @FXML
    public TextField urlText;
    @FXML
    public Button collBtn;
    @FXML
    public TextField dirText;

    final DirectoryChooser dirChooser = new DirectoryChooser();


    // @PostConstruct
    public void seleDirOld(ActionEvent actionEvent) {
        dirSelBtn.setOnAction(event -> {
            File file = dirChooser.showDialog(null);
            if (file != null) {
                dirText.setText(file.getAbsolutePath());
            }
        });
    }

    public void seleDir() {
        File file = dirChooser.showDialog(null);
        if (file != null) {
            dirText.setText(file.getAbsolutePath());
        }
    }

    @FXML
    public void collect(ActionEvent actionEvent) {
        colButSet("采集进行中", false, true);
        ThreadPools.poolExecutor.execute(() -> {
            try {
                String url = urlText.getText();
                /*if (GetPage.isDeled(url)) {
                    AlertUtils.showAlter(Alert.AlertType.INFORMATION, "问题不存在或已被删除");
                    return;
                }*/
                GetPage.get(url, dirText.getText(), onlyPageCheck.isSelected(), onlyPublishCheck.isSelected());
            } catch (Exception e) {
                log.error("采集异常", e);
                AlertUtils.showAlter(Alert.AlertType.INFORMATION, "采集异常" + e.getMessage());
            }
            log.info("采集完成");
            Platform.runLater(() -> {
                colButSet("采集", true, false);
            });
        });
    }

    /**
     * 更改按钮状态 文字
     *
     * @param title    按钮名字
     * @param addClass class
     * @param disable  状态
     */
    private void colButSet(String title, boolean addClass, boolean disable) {
        collBtn.setText(title);
        if (addClass) {
            collBtn.getStyleClass().remove("btn-info");
        } else {
            collBtn.getStyleClass().add("btn-info");
        }
        collBtn.setDisable(disable);
    }
}
